<!-- //pages数组中第一项表示应用启动页，参考：https://uniapp.dcloud.io/collocation/pages -->
<template>
  <view class="w-full">
    <div class="confirmLine p-2 rounded-md m-2 gap-2 flex-col flex">
      <uni-forms ref="form" :modelValue="formData" :rules="rules" label-position="top">

        <uni-forms-item name="name" class="w-full" label="真实姓名">
          <uni-easyinput prefixIcon="input" v-model="formData.name" placeholder="输入您的真实姓名"></uni-easyinput>
        </uni-forms-item>

        <uni-forms-item name="avatar" class="w-full" label="头像">
          <uni-file-picker v-model="formData.avatar" file-mediatype="image" mode="grid" file-extname="png,jpg" :limit="1"
            @progress="progressPic" @successPic="successPic" @failPic="failPic"
            @select="selectAvatar">请上传真实头像照片(png,jpg格式)</uni-file-picker>
        </uni-forms-item>

        <uni-forms-item label="手机号码" name="phone">
          <uni-easyinput prefixIcon="input" v-model="formData.phone" placeholder="输入有效手机号"></uni-easyinput>
        </uni-forms-item>

        <uni-forms-item name="datetimesingle" class="w-full" label="工作日期">
          <uni-datetime-picker type="date" return-type="timestamp" v-model="formData.datetimesingle" />
        </uni-forms-item>


        <uni-forms-item name="area" class="w-full" label="所在地区">
          <picker class="pickerList flex-1 bg-gray-100 p-2 rounded-md" mode="multiSelector" :range="newProvinceDataList"
            :value="multiIndex" @change="pickerChange" @columnchange="pickerColumnchange">
            {{
              formData.area
            }}
          </picker>
        </uni-forms-item>

        <uni-forms-item label="详细地址" name="location">
          <uni-easyinput prefixIcon="input" v-model="formData.location" placeholder="请填写详细地址"></uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="身份证号" name="IDNumber">
          <uni-easyinput prefixIcon="input" v-model="formData.IDNumber" placeholder="输入身份证号码"></uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="证件图片" name="IDPics">
          <uni-file-picker v-model="IDPics" file-mediatype="image" mode="grid" file-extname="png,jpg" :limit="2"
            @progress="progressPic" @success="successPic" @fail="failPic" @select="selectPic">请上传身份证正反面照片(png,jpg格式)
          </uni-file-picker>
        </uni-forms-item>

        <div class="flex py-2 items-center text-red-500">
          以上信息请务必填写真实正确，因填写错误或不真实所产生的后果和责任将由本人承担。
        </div>


      </uni-forms>

      <button class="bg-[#1483F2] w-full" @click="submit">提交</button>
    </div>
  </view>
</template>

<script>
//选择地区相关数据存放位置
import { provinceData } from '../../static/data/provinceData.js';
import { useUploadFile } from '../../composables/uploadFile.js';
export default {
  data() {
    return {
      //选择地区相关数据
      oldProvinceDataList: provinceData.data,
      newProvinceDataList: [
        [], [], []
      ],
      multiIndex: [0, 0, 0],
      //

      //上传图片
      imageValue: [],
      filePaths: [],
      avatarPath: '',

      //表单验证
      formData: {
        name: '',
        avatar: '',
        phone: '',
        datetimesingle: "2000-01-01",//工作日期
        location: '',
        IDNumber: '',
        IDPics: [],
        area: '请选择地区',
      },

      rules: {
        //对area字段进行验证
        area: {
          rules: [
            {
              validateFunction: function (rule, value, data, callback) {
                if (value == '请选择地区') {
                  callback('请选择地区');
                }
              }
            }
          ]
        },

        // 对name字段进行验证
        name: {
          rules: [{
            required: true,
            errorMessage: '请输入姓名',
          },
          {
            minLength: 2,
            maxLength: 5,
            errorMessage: '姓名长度在 {minLength} 到 {maxLength} 个字符',
          }
          ]
        },

        //对avatar字段进行验证
        // avatar: {
        //   rules: [{
        //     required: true,
        //     errorMessage: '请选择头像',
        //   }],
        // },

        //对phone字段进行验证
        phone: {
          rules: [{
            required: true,
            errorMessage: '请输入有效手机号码',
          },
          {
            validateFunction: function (rule, value, data, callback) {
              let iphoneReg = (
                /^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/
              ); //手机号码
              if (!iphoneReg.test(value)) {
                callback('手机号码格式不正确，请重新填写')
              }
            }
          }
          ]
        },

        //对datetimesingle字段进行验证
        datetimesingle: {
          rules: [
            {
              validateFunction: function (rule, value, data, callback) {
                if (value == "2000-01-01") {
                  callback('请选择工作日期');
                }
              }
            }
          ]
        },

        //对location进行验证
        location: {
          rules: [{
            required: true,
            errorMessage: '请输入详细地址',
          },
          ]
        },

        // 对IDNumber字段进行验证
        IDNumber: {
          rules: [{
            required: true,
            errorMessage: '请输入身份证号码',
          },
          {
            validateFunction: function (rule, value, data, callback) {
              let iphoneReg = (
                /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
              ); //
              if (!iphoneReg.test(value)) {
                callback('身份证格式不正确，请重新填写')
              }
            }
          }
          ]
        },

        //对IDPic字段进行验证
        // IDPics: {
        //   rules: [{
        //     required: true,
        //     errorMessage: '请上传身份证正反面照片',
        //   }],
        // },
      }

    }
  },

  //选择地区相关数据
  onLoad() {

    for (let i = 0; i < this.oldProvinceDataList.length; i++) {
      this.newProvinceDataList[0].push(this.oldProvinceDataList[i].name);
    }
    for (let i = 0; i < this.oldProvinceDataList[0].city.length; i++) {
      this.newProvinceDataList[1].push(this.oldProvinceDataList[0].city[i].name);
    }
    for (let i = 0; i < this.oldProvinceDataList[0].city[0].area.length; i++) {
      this.newProvinceDataList[2].push(this.oldProvinceDataList[0].city[0].area[i]);
    }
  },
  //

  //验证规则
  onReady() {
    // 需要在onReady中设置规则
    this.$refs.form.setRules(this.rules)
  },

  methods: {
    input(e) {
      console.log(e.target.value)
    },

    //关于图片上传相关方法
    // 获取上传状态
    selectPic(e) {
      console.log(e)
      this.filePaths.push(e.tempFilePaths[0])
    },
    selectAvatar(e) {
      console.log(e)
      this.avatarPath = e.tempFilePaths[0]
    },

    //上传图片
    async uploadAvatar() {
      this.formData.avatar = await useUploadFile(this.avatarPath)
    },

    async uploadIDPics() {
      console.log(this.filePaths)
      for (const filePath of this.filePaths) {
        const data = await useUploadFile(filePath)
        this.formData.IDPics.push(data)
        console.log(data)
      }
    },
    // 获取上传进度
    progressPic(e) {
      console.log('上传进度：', e)
    },

    // 上传成功
    successPic(e) {
      console.log('上传成功')
    },

    // 上传失败
    failPic(e) {
      console.log('上传失败：', e)
    },
    //


    //选择地区
    // 省市区确认事件
    pickerChange(e) {
      this.multiIndex = e.detail.value;
      this.formData.area = `${this.newProvinceDataList[0][this.multiIndex[0]]}--${this.newProvinceDataList[1][this.multiIndex[1]]}--${this.newProvinceDataList[2][this.multiIndex[2]]}`
    },
    pickerColumnchange(e) {
      if (e.detail.column === 0) {
        this.multiIndex[0] = e.detail.value
        this.newProvinceDataList[1] = this.oldProvinceDataList[this.multiIndex[0]].city.map((item, index) => {
          return item.name
        })
        if (this.oldProvinceDataList[this.multiIndex[0]].city.length === 1) {
          this.newProvinceDataList[2] = this.oldProvinceDataList[this.multiIndex[0]].city[0].area.map((item, index) => {
            return item
          })
        } else {
          this.newProvinceDataList[2] = this.oldProvinceDataList[this.multiIndex[0]].city[this.multiIndex[1]].area.map((item, index) => {
            return item
          })
        }
        this.multiIndex.splice(1, 1, 0)
        this.multiIndex.splice(2, 1, 0)
      }
      if (e.detail.column === 1) {
        this.multiIndex[1] = e.detail.value
        this.newProvinceDataList[2] = this.oldProvinceDataList[this.multiIndex[0]].city[this.multiIndex[1]].area.map((item, index) => {
          return item
        })
        this.multiIndex.splice(2, 1, 0)
      }
      if (e.detail.column === 2) {
        this.multiIndex[2] = e.detail.value
      }
    },


    //提交表单
    /**
     * 复写 binddata 方法，如果只是为了校验，无复杂自定义操作，可忽略此方法
     * @param {String} name 字段名称
     * @param {String} value 表单域的值
     */
    // binddata(name,value){
    // 通过 input 事件设置表单指定 name 的值
    //   this.$refs.form.setValue(name, value)
    // },
    // 触发提交表单
    submit() {
      this.$refs.form.validate().then(async formData => {
        await this.uploadAvatar()
        await this.uploadIDPics()
        console.log(formData)
        uni.request({
          url: '/user',
          method: 'PUT',
          data: this.formData,
          success: ({ data }) => {
            uni.navigateTo({ url: '/pages/checkidsuccess/checkidsuccess' })
            console.log(data)
          }
        })
      }).catch(err => {
        uni.showToast({
          title: err
        })
      })
    }
  }
}

</script>

<style scoped>
.confirmLine {
  border: 1px solid rgba(31, 31, 31);
}

.uni-mt-5 {
  margin-top: 5px;
}
</style>